import { dynamicStore } from "@store/dynamic"
import {get,post} from "@utils/http"
import dayjs from "dayjs"
import { FormEvent } from "miniprogram/@types/Event"
import { createStoreBindings } from 'mobx-miniprogram-bindings'
// pages/comment/comment.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    comments:[],
    dynamicdetail:{},
    comment:""
  },
  deleteComments(){
    
  },
  async getComments(){
    const detail=this.data.dynamicdetail
    const res=await get("/dynamics/comment",{
      id:detail.id
    })
    this.setData({
      comments:res.map(item=>{
        const ts=item.updatedAt
        item.time=dayjs(ts).format("YYYY/MM/DD")
        return item
      })
    })
  },
  shareDynamic(e:any){
    const index=e.currentTarget.dataset.index
   getApp().globalData.dynamic=this.data.dynamicList[index]
    wx.showShareMenu({ // 是否使用带 shareTicket 的转发
      menus: ['shareAppMessage', 'shareTimeline'] // 显示的分享按钮类型
    })
  },
  preViewImage(e:FormEvent<{src:string}>){
    const {src}=e.currentTarget.dataset
    wx.previewImage({
      urls:this.data.dynamicdetail.srcs,
      current:src
    })
 },
  getmessage(e:any){
    this.setData({
      comment:e.detail.value
    })
  },
  async createComment(){
    const comment=this.data.comment
    if(!comment.trim())return
    const id=this.data.dynamicdetail.id
    this.setData({
      comment:""
    })
    const res=await post("/dynamics/comment",{
      content:comment,
      dyId:id,
      parentId:null
    })
    this.setDynamicList(this.data.dynamicList.map(item=>{
      if(item.id===id){
        item.commentnumber++
        return item
      }else{
        return item
      }
    }))
    this.getComments()
  },

  /**
   * 生命周期函数--监听页面加载
   */
   onLoad(option:any) {
    this.storeBindings=createStoreBindings(this,{
      store:dynamicStore,
      fields :{
        dynamicList:()=>dynamicStore.dynamicList
      },
      actions:["setDynamicList"],
    })
    const dynamicdetail=JSON.parse(option.detail)
    this.setData({
      dynamicdetail
    })
    this.getComments()
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})